package fun.stgoder.easydarwin.jobs.ctl.view;

import fun.stgoder.easydarwin.jobs.bl.API;
import fun.stgoder.easydarwin.jobs.bl.model.api.Folder;
import fun.stgoder.easydarwin.jobs.bl.model.api.Player;
import fun.stgoder.easydarwin.jobs.bl.model.api.Pusher;
import fun.stgoder.easydarwin.jobs.comm.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/stream")
public class Stream {

    @GetMapping("/pushers")
    public ModelAndView pushers(ModelAndView mv) throws Exception {

        mv.setViewName("pushers");
        mv.addObject("title", "pushers");
        mv.addObject("tab", "pushers");

        List<Pusher> pushers = API.pushers(0, 100, null, null, null).getRows();
        mv.addObject("pushers", pushers);

        return mv;
    }

    @GetMapping("/players")
    public ModelAndView players(ModelAndView mv) throws Exception {

        mv.setViewName("players");
        mv.addObject("title", "players");
        mv.addObject("tab", "players");

        List<Player> players = API.players(0, 100, null, null, null).getRows();
        mv.addObject("players", players);

        return mv;
    }

    @GetMapping("/folders")
    public ModelAndView folders(ModelAndView mv) throws Exception {

        mv.setViewName("folders");
        mv.addObject("title", "folders");
        mv.addObject("tab", "folders");

        List<Folder> folders = API.folders(0, 100, null, null, null).getRows();
        mv.addObject("folders", folders);

        return mv;
    }

    @PostMapping("/start")
    public ModelAndView start(@RequestParam("rtsp") String rtsp, @RequestParam("streamId") String streamId,
                              @RequestParam(value = "transType", required = false) String transType,
                              @RequestParam(value = "idleTimeout", required = false, defaultValue = "0") int idleTimeout,
                              @RequestParam(value = "heartbeatInterval", required = false, defaultValue = "0") int heartbeatInterval,
                              ModelAndView mv) throws Exception {

        mv.setViewName("redirect:/stream/pushers");

        rtsp = StringUtils.strip(rtsp);
        streamId = StringUtils.strip(streamId);

        if (Constants.PRE_RECORD)
            streamId = "/" + streamId;
        API.start(rtsp, streamId, transType, idleTimeout, heartbeatInterval);

        return mv;
    }

    @PostMapping("/stop")
    public ModelAndView stop(@RequestParam("id") String id, ModelAndView mv) throws Exception {

        mv.setViewName("redirect:/stream/pushers");

        API.stop(id);

        return mv;
    }
}
